package cn.xiaoliu.hrm.service;

import cn.xiaoliu.hrm.domain.LoginUser;
import cn.xiaoliu.hrm.domain.Permission;
import cn.xiaoliu.hrm.mapper.LoginUserMapper;
import cn.xiaoliu.hrm.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetail implements UserDetailsService{
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据名字从数据库查询
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser = loginUserMapper.selectOne(loginUser);
        ArrayList<SimpleGrantedAuthority> authens = new ArrayList<SimpleGrantedAuthority>();
        //判断loginuser是否存在
        if (loginUser != null){
            List<Permission> permissions = loginUserMapper.findPermissions(loginUser.getId());
            permissions.stream().forEach(permission -> {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
                authens.add(authority);
            });
        }
        //封装UserDetails，包括用户的账号密码和权限
        User user = new User(loginUser.getUsername(), loginUser.getPassword(), authens);
        return user;
    }

}
